﻿$(document).ready(function () {
    SetFocusOnFirstTextBox();
    DisableSearchButtonIfSearchTermIsEmpty('');

    $("input#search").keyup(function (data) {
        var searchTerm = GetSearchTermFromTextBox();
        DisableSearchButtonIfSearchTermIsEmpty(searchTerm);

        if (data.which == 13 && searchTerm.length > 0) {
            NavigateToSearch(searchTerm);
        }
    });

    $('#searchButton').click(function () {
        var searchTerm = GetSearchTermFromTextBox();

        NavigateToSearch(searchTerm);
    });

    $("input#search").autocomplete(
               {
                   source: autoCompleteUrl,
                   select: function (event, ui) {
                       window.location = redirectUrl + ui.item.id;
                   }
               }
        );
});

    function SetFocusOnFirstTextBox() {
        var textBoxes = $("input[type='text']:enabled");

        if (textBoxes.length == 0) {
            return;
        }

        if (textBoxes.length == 1) {
            textBoxes[0].focus();
        }
        else {
            textBoxes[1].focus();
        }
    }

     function DisableSearchButtonIfSearchTermIsEmpty(searchTerm) {
        var searchButtonObject = $('#searchButton');
        
        if (searchTerm.length == 0) {
           searchButtonObject.attr('disabled','disabled');
        }
        else{
            searchButtonObject.removeAttr('disabled');
        }
     }

    function GetSearchTermFromTextBox() {
        return $("input#search").val();
    }

    function NavigateToSearch(searchTerm) {
        window.location = searchUrl + searchTerm;
    }

    function SetAutoCompleteUrls(autocompleteSourceUrl, autocompelteSearchUrl, autocompleteRedirectUrl) {
        autoCompleteUrl = autocompleteSourceUrl;
        searchUrl = autocompelteSearchUrl.replace(/%20/g,'');
        redirectUrl = autocompleteRedirectUrl.replace(/%20/g,'');
    }

    var autoCompleteUrl = null;
    var redirectUrl = null;
    var searchUrl = null;